package com.thx.user.action;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.thx.common.struts2.ExtendPropertyAction;
import com.thx.common.util.AppContext;
import com.thx.common.util.PasswordUtil;
import com.thx.common.web.ActionResult;
import com.thx.common.web.WebConstant;
import com.thx.log.LogUtil;
import com.thx.org.model.Department;
import com.thx.org.service.DepartmentManager;
import com.thx.role.model.Role;
import com.thx.role.service.RoleManager;
import com.thx.user.model.User;
import com.thx.user.service.UserManager;
import com.thx.user.util.ModuleConstant;

/**
 * 建立日期 : Jul 31, 2012 4:25:39 PM<br>
 * 作者 : 贾红磊<br>
 * 模块 : <br>
 * 描述 : <br>
 * 修改历史: 序号 日期 修改人 修改原因 <br>
 * 1 <br>
 * 2 <br>
 */
@Namespace("/user")
@Action(value = "user", results = {
    @Result(name = "input", location = "/pages/system/user/input.jsp"),
    @Result(name = "list", location = "/pages/system/user/list.jsp"),
    @Result(name = "view", location = "/pages/system/user/detail.jsp"),
    @Result(name = "userlink", location = "/pages/system/user/link.jsp"),
    @Result(name = "resetPwd", location = "/pages/system/user/resetPwd.jsp"),
    @Result(name = "json", type = "json", params = {"root", "result"})})
@Controller
@Scope("prototype")
public class UserAction extends ExtendPropertyAction<User> {

  private static final long serialVersionUID = 1L;

  protected Role role;

  protected String deptId;

  protected String[] roleIds;

  protected List<Role> rolelist;

  @Autowired
  protected UserManager userMgr;

  @Autowired
  protected DepartmentManager deptMgr;

  @Autowired
  protected RoleManager roleMgr;

  protected String oldPwd;

  public UserAction() {}

  protected void doList() throws Exception {
    list =
        userMgr.searchUser(entity.getUserName(), entity.getRealName(), entity.getEmail(),
            entity.getMobilePhone(), deptId);
  }

  public String getAll() {
    try {
      list = userMgr.getAll();
    } catch (Exception e) {
      logger.error(e.getMessage(), e);
    }
    return SUCCESS;
  }

  protected void doSave() throws Exception {
    try {
      if (StringUtils.isBlank(id)) {
        saveUser();
      } else {
        editUser();
      }
    } catch (Exception e) {
      if (StringUtils.isBlank(id)) {
        setResult(ActionResult.FAIL, "添加失败！");
      } else {
        setResult(ActionResult.FAIL, "修改失败！");
      }
      logger.error(e.getMessage(), e);
    }
  }

  protected void editUser() {

    User sessionUser = (User) getSession().getAttribute(WebConstant.KEY_USER);

    User user = userMgr.get(id);
    if ("systemReset".equals(message)) {
      if (StringUtils.isNotBlank(entity.getPassword())) {
        // 加密密码
        String pwd = PasswordUtil.encrypt(entity.getPassword(), user.getSalt());

        // 更新加密类型
        String algorithmName = AppContext.getProperties(WebConstant.ENCRYPTED_TYPE);

        userMgr.setPwd(pwd, algorithmName, user.getUserId(), sessionUser.getUserId(), new Date());

        setResult(ActionResult.SUCCESS, "重置成功！");
        LogUtil.log(ModuleConstant.USER_MANAGER, LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "重置用户密码");
      }
    } else {
      user.setUserName(StringUtils.strip(entity.getUserName()));
      user.setRealName(StringUtils.strip(entity.getRealName()));
      user.setEmail(StringUtils.strip(entity.getEmail()));
      user.setMobilePhone(StringUtils.strip(entity.getMobilePhone()));
      user.getRoles().clear();
      if (roleIds != null && roleIds.length > 0) {
        for (int i = 0; i < roleIds.length; i++) {
          role = roleMgr.get(roleIds[i]);
          user.addRoles(role);
        }
      }
      Department deprt = deptMgr.get(deptId);
      user.setDepartment(deprt);
      user.setLastUpdateDate(new Date());
      userMgr.save(user);
      setResult(ActionResult.SUCCESS, "修改成功！");
      LogUtil.log(ModuleConstant.USER_MANAGER, LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "修改用户信息");
    }

    if (sessionUser != null && sessionUser.getUserId().equals(user.getUserId())) {
      getSession().setAttribute(WebConstant.KEY_USER, user);
    }
  }

  protected void saveUser() {
    if (roleIds != null && roleIds.length > 0) {
      for (int i = 0; i < roleIds.length; i++) {
        role = roleMgr.get(roleIds[i]);
        entity.addRoles(role);
      }
    }
    Department deprt = deptMgr.get(deptId);
    if (deprt != null) {
      entity.setDepartment(deprt);
    }
    entity.setUserName(StringUtils.strip(entity.getUserName()));
    entity.setRealName(StringUtils.strip(entity.getRealName()));
    entity.setMobilePhone(StringUtils.strip(entity.getMobilePhone()));
    entity.setEmail(StringUtils.strip(entity.getEmail()));
    entity.setPassword(entity.getPassword());
    entity.setCreateDate(new Date());
    String comId = AppContext.getCurrentComId();
    entity.setComId(comId);
    entity.setStatus("1");
    entity.setLastUpdateDate(new Date());

    userMgr.save(entity);

    setResult(ActionResult.SUCCESS, "添加成功！");
    LogUtil.log(ModuleConstant.USER_MANAGER, LogUtil.ACTION_ADD, LogUtil.RESULT_SUCCESS, "新增用户");
  }

  protected void doView() throws Exception {
    if (StringUtils.isNotBlank(id)) {
      entity = userMgr.get(id);
      if (entity == null) {
        setResult(ActionResult.FAIL, "要查看的记录不存在！！！");
      }
    } else {
      setResult(ActionResult.FAIL, "服务器异常！");
    }
  }

  public String userLink() {
    if (StringUtils.isNotBlank(id)) {
      entity = userMgr.get(id);
      if (entity == null) {
        setResult(ActionResult.FAIL, "要查看的记录不存在！！！");
      }
    } else {
      setResult(ActionResult.FAIL, "服务器异常！");
    }
    return "userlink";
  }

  protected void doDelete() throws Exception {
    if (StringUtils.isNotBlank(id)) {
      userMgr.delete(id);
      setResult(ActionResult.SUCCESS, "删除成功！！！");
      LogUtil.log(ModuleConstant.USER_MANAGER, LogUtil.ACTION_DELETE, LogUtil.RESULT_SUCCESS,
          "删除用户");
    } else {
      setResult(ActionResult.FAIL, "服务器异常！");
    }
  }

  protected void doDelMulti() throws Exception {
    if (delId != null && delId.length > 0) {
      delId = delId[0].split(",");
      userMgr.delMulti(delId);
      setResult(ActionResult.SUCCESS, "删除成功！！！");
      LogUtil.log(ModuleConstant.USER_MANAGER, LogUtil.ACTION_DELETE, LogUtil.RESULT_SUCCESS,
          "删除用户");
    } else {
      setResult(ActionResult.FAIL, "服务器异常！");
    }
  }

  public String setDelStatus() {
    if (delId != null && delId.length > 0) {
      delId = delId[0].split(",");
      userMgr.delStatus(delId);
      setResult(ActionResult.SUCCESS, "删除成功！！！");
      LogUtil.log(ModuleConstant.USER_MANAGER, LogUtil.ACTION_DELETE, LogUtil.RESULT_SUCCESS,
          "删除用户");
    } else {
      setResult(ActionResult.FAIL, "服务器异常！");
    }
    return JSON;
  }

  protected void doInput() throws Exception {
    if (StringUtils.isNotBlank(id)) {
      entity = userMgr.get(id);
      if (entity == null) {
        setResult(ActionResult.FAIL, "要修改的记录不存在！！！");
      } else {
        if (entity.getDepartment() != null) {
          deptId = entity.getDepartment().getDepId();
        }
      }
    }
    rolelist = roleMgr.searchAllRoles(null);
  }

  public String sysResetPwd() {
    if (StringUtils.isNotBlank(id)) {
      entity = userMgr.get(id);
      if (entity == null) {
        setResult(ActionResult.FAIL, "要修改的记录不存在！！！");
      }
    }
    return INPUT;
  }

  /**
   * 用户重置密码链接action
   */
  public String resetPwd() {
    return "resetPwd";
  }

  /**
   * 提交新密码
   */
  public String savePwd() {
    try {
      User user = (User) getSession().getAttribute(WebConstant.KEY_USER);
      if (user != null && entity.getPassword() != null) {
        // 加密密码
        String pwd = PasswordUtil.encrypt(entity.getPassword(), user.getSalt());

        // 更新加密类型
        String algorithmName = AppContext.getProperties(WebConstant.ENCRYPTED_TYPE);

        userMgr.setPwd(pwd, algorithmName, user.getUserId(), user.getUserId(), new Date());
        setResult(ActionResult.SUCCESS, "修改成功！");
        LogUtil.log(ModuleConstant.USER_MANAGER, LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "修改自身密码");
        user.setPassword(pwd);
      } else {
        setResult(ActionResult.SUCCESS, "无法修改密码！");
      }
    } catch (Exception e) {
      setResult(ActionResult.SUCCESS, "修改失败！");
      logger.error(e.getMessage(), e);
    }
    return JSON;
  }

  /**
   * 修改密码时验证密码旧密码是否正确
   */
  public void checkPassword() {
    try {
      User user = (User) getSession().getAttribute(WebConstant.KEY_USER);
      if (user != null && StringUtils.isNotBlank(oldPwd)) {
        if (PasswordUtil.isMatch(oldPwd, user.getPassword(), user.getSalt())) {
          writeJson("true");
        } else {
          writeJson("false");
        }
      }
    } catch (Exception e) {
      setResult(ActionResult.FAIL, "服务器异常！");
    }
  }

  /**
   * 验证用户名是否存在
   */
  public void checkUserName() {
    try {
      User user = userMgr.findByName(StringUtils.strip(entity.getUserName()));
      if (user == null)
        writeJson("true");
      else {
        if (StringUtils.isNotBlank(id) && id.equals(user.getUserId())) {
          // --修改时用户名和原来的可以保持一致
          writeJson("true");
        } else {
          writeJson("false");
        }

      }

    } catch (Exception e) {
      setResult(ActionResult.FAIL, "服务器异常！");
    }
  }

  /**
   * 验证手机号是否存在
   */
  public void checkMobilePhone() {
    try {
      User user = userMgr.findByPhone(StringUtils.strip(entity.getMobilePhone()));
      if (user == null)
        writeJson("true");
      else {
        if (StringUtils.isNotBlank(id) && id.equals(user.getUserId())) {
          // --修改时用户名和原来的可以保持一致
          writeJson("true");
        } else {
          writeJson("false");
        }

      }

    } catch (Exception e) {
      setResult(ActionResult.FAIL, "服务器异常！");
    }
  }

  /**
   * 验证邮箱是否存在
   */
  public void checkEmail() {
    try {
      User user = userMgr.findByEmail(StringUtils.strip(entity.getEmail()));
      if (user == null)
        writeJson("true");
      else {
        if (StringUtils.isNotBlank(id) && id.equals(user.getUserId())) {
          // --修改时用户名和原来的可以保持一致
          writeJson("true");
        } else {
          writeJson("false");
        }

      }

    } catch (Exception e) {
      setResult(ActionResult.FAIL, "服务器异常！");
    }
  }

  public UserManager getUserMgr() {
    return userMgr;
  }

  public void setUserMgr(UserManager userMgr) {
    this.userMgr = userMgr;
  }

  public String getOldPwd() {
    return oldPwd;
  }

  public void setOldPwd(String oldPwd) {
    this.oldPwd = oldPwd;
  }

  public RoleManager getRoleMgr() {
    return roleMgr;
  }

  public void setRoleMgr(RoleManager roleMgr) {
    this.roleMgr = roleMgr;
  }

  public DepartmentManager getDeptMgr() {
    return deptMgr;
  }

  public void setDeptMgr(DepartmentManager deptMgr) {
    this.deptMgr = deptMgr;
  }

  public Role getRole() {
    return role;
  }

  public void setRole(Role role) {
    this.role = role;
  }

  public List<Role> getRolelist() {
    return rolelist;
  }

  public void setRolelist(List<Role> rolelist) {
    this.rolelist = rolelist;
  }

  public String getDeptId() {
    return deptId;
  }

  public void setDeptId(String deptId) {
    this.deptId = deptId;
  }

  public String[] getRoleIds() {
    return roleIds;
  }

  public void setRoleIds(String[] roleIds) {
    this.roleIds = roleIds;
  }

}
